package com.cold.legendary.bprocess.trigger;

import com.cold.legendary.bprocess.BProcessService;
import com.cold.legendary.bprocess.common.constance.BErrorCodeEnum;
import com.cold.legendary.bprocess.common.exception.BProcessException;
import com.cold.legendary.bprocess.context.ins.BPointIns;
import com.cold.legendary.bprocess.context.run.BContext;
import com.cold.legendary.bprocess.db.model.TbProcessRequest;
import com.cold.legendary.bprocess.db.repository.ProcessRequestRepository;
import com.cold.legendary.bprocess.trigger.enums.TriggerModeEnum;
import com.cold.legendary.bprocess.trigger.helper.ProcessRequestCheckHelper;
import com.cold.legendary.bprocess.trigger.transaction.BProcessTransactionService;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author cold
 * @since 2023/3/10
 */
@Slf4j
public abstract class AbstractBProcessTriggerService implements BProcessTriggerService {
    @Resource
    protected BProcessTriggerServiceFactory factory;
    @Resource
    protected ProcessRequestCheckHelper processRequestCheckHelper;
    @Resource
    protected BProcessTransactionService bProcessTransactionService;
    @Resource
    protected BProcessService bProcessService;
    @Resource
    protected ProcessRequestRepository processRequestRepository;

    /**
     * 基础校验
     * @param bContext 上下文
     * @param triggerBPointIns 节点实例
     * @param qryProcessRequest 查询的请求记录
     */
    protected void baseCheck(BContext bContext, BPointIns triggerBPointIns, TbProcessRequest qryProcessRequest) {

        String bizId = bContext.getBizId();
        String merchantId = bContext.getMerchantId();
        String processId = bContext.getProcessId();

        if (null == triggerBPointIns) {
            log.info("triggerBPointIns不能为空!bizId={}, merchantId={},processId={}", bizId, merchantId, processId);
            throw new BProcessException(BErrorCodeEnum.SYS_TRIGGERBPOINTINS_NONE_ERROR);
        }
        if (!triggerBPointIns.getPointId().equals(qryProcessRequest.getPointId())) {
            log.error("节点不匹配,不允许流转,当前节点={}, 将要流转的节点={}",
                    qryProcessRequest.getPointId(), triggerBPointIns.getPointId());
            throw new BProcessException(BErrorCodeEnum.SYS_POINT_NOT_MATCH_ERROR);
        }
    }

    /**
     * 获取触发模式,方便注册
     *
     * @return 触发模式
     */
    protected abstract TriggerModeEnum getTriggerModeEnum();


    @PostConstruct
    protected void init() {
        factory.register(getTriggerModeEnum(), this);
    }

}
